﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DbManager;
using DbManager.DataManager;
using DbManager.QueryBuilder.DbEntity;
using DbManager.QueryBuilder.DbEntity.IND.Gorod;
using DbManager.QueryBuilder.DbEntity.Pot;
using DbManager.QueryBuilder.DbEntity.Transport;
using TAProject.UI.Order;

namespace TAProject.UI.Service.Price
{
    public partial class FormManagePot : FormTemplate
    {
        private readonly Form _parentForm;
        private readonly IDataManager _dataManager;
        private readonly IConnectionManager _connectionManager;
        private readonly AEntityPot _aEntityPot;

        private int _currentRowIndex;
        private int _napravlenieId;
        private DataTable _dataTableMain;

         public FormManagePot(Form parentForm, IDataManager dataManager, IConnectionManager connetctionManager)
            : base(parentForm)
        {
            InitializeComponent();

            _parentForm = parentForm;
            _dataManager = dataManager;
            _connectionManager = connetctionManager;

            _aEntityPot = new EntityPot();

            comboBoxNapravlenie.SelectedValueChanged += ComboBoxNapravlenieSelectedValueChanged;
            checkBoxShowAll.CheckedChanged += CheckBoxShowAllCheckedChanged;

            UpdateDataGrid();

            _parentForm.Enabled = false;
        }

        private void FormManageProezd_EnabledChanged(object sender, EventArgs e)
        {
            if (dataGridView.Rows.Count > 0)
                dataGridView.Rows[_currentRowIndex].Selected = true;
        }

        private void DataGridViewCellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex < 0) return;
            _currentRowIndex = e.RowIndex;
        }

        #region Buttons events

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            var formSelectItem = _napravlenieId != 0
                                     ? new FormSelectItem(this, new EntityGorod(), _dataManager, _connectionManager,
                                                          "Выберите город", _napravlenieId, "Hide_IDNapravlenie")
                                     : new FormSelectItem(this, new EntityGorod(), _dataManager, _connectionManager,
                                                          "Выберите город");
            formSelectItem.ShowDialog(this);
            if (formSelectItem.Id == null || formSelectItem.Id == 0) return;
            _aEntityPot.IDGorod = formSelectItem.Id.Value;

            formSelectItem = new FormSelectItem(this, new EntityTransport(), _dataManager, _connectionManager,
                                                "Выберите транспорт");
            formSelectItem.ShowDialog(this);
            if (formSelectItem.Id == null || formSelectItem.Id == 0) return;
            _aEntityPot.IDTransport = formSelectItem.Id.Value;

            var formDoublePrice = new FormDoublePrice(this);
            formDoublePrice.ShowDialog(this);
            if (formDoublePrice.PriceAdult == null || formDoublePrice.PriceChild == null) return;
            _aEntityPot.PriceAdult = formDoublePrice.PriceAdult.Value;
            _aEntityPot.PriceChild = formDoublePrice.PriceChild.Value;

            var rowAffected = _dataManager.ManageDataInDb(_aEntityPot.GetInsertQuery(),
                                                          _connectionManager.GetConnection());
            _currentRowIndex = 0;
            dataGridView.Rows[_currentRowIndex].Selected = true;
            if (rowAffected == 0)
                MessageBox.Show("Ошибка добавления данных");
            else
                UpdateDataGrid();
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow != null)
            {
                var currentRow = dataGridView.CurrentRow.Index;

                _aEntityPot.ID = (int) dataGridView.Rows[currentRow].Cells["Hide_IDPot"].Value;
                _aEntityPot.IDTransport = (int) dataGridView.Rows[currentRow].Cells["Hide_IDTransport"].Value;
                _aEntityPot.IDGorod = (int) dataGridView.Rows[currentRow].Cells["Hide_IDGorod"].Value;

                _aEntityPot.PriceAdult = (decimal) dataGridView.Rows[currentRow].Cells["Цена проезда взросл"].Value;
                _aEntityPot.PriceChild = (decimal) dataGridView.Rows[currentRow].Cells["Цена проезда детск"].Value;

                var form = new FormDoublePrice(this, _aEntityPot.PriceAdult, _aEntityPot.PriceChild);
                form.ShowDialog(this);

                if (form.PriceAdult == null || form.PriceChild == null)
                {
                    MessageBox.Show("Ошибка обновления данных");
                    return;
                }
                _aEntityPot.PriceAdult = form.PriceAdult.Value;
                _aEntityPot.PriceChild = form.PriceChild.Value;

                var rowAffected = _dataManager.ManageDataInDb(_aEntityPot.GetUpdateQuery(),
                                                              _connectionManager.GetConnection());
                _currentRowIndex = 0;
                dataGridView.Rows[_currentRowIndex].Selected = true;
                if (rowAffected == 0)
                    MessageBox.Show("Ошибка обновления данных");
                else
                    UpdateDataGrid();
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow != null)
            {
                _aEntityPot.ID = (int) dataGridView.Rows[_currentRowIndex].Cells["Hide_IDPot"].Value;
                var rowAffected = _dataManager.ManageDataInDb(_aEntityPot.GetDeleteQuery(),
                                                              _connectionManager.GetConnection());
                _currentRowIndex = 0;
                dataGridView.Rows[_currentRowIndex].Selected = true;
                if (rowAffected == 0)
                {
                    MessageBox.Show("Ошибка удаления, повторите попытку.");
                }
            }

            UpdateDataGrid();
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            FormClose();
        }

        private void FormClose()
        {
            _parentForm.Enabled = true;
            Close();
        }

        #endregion

        private void ComboBoxNapravlenieSelectedValueChanged(object sender, EventArgs e)
        {
            if (comboBoxNapravlenie.Items.Count < 1 || comboBoxNapravlenie.SelectedValue == null) return;
            _napravlenieId = (int) comboBoxNapravlenie.SelectedValue;
            var dataTableFilteredByNapravlenie = _dataTableMain.AsEnumerable().
                Where(row => row.Field<int>("Hide_IDNapravlenie") == _napravlenieId).CopyToDataTable();
            CustomFillDataGrid(dataTableFilteredByNapravlenie);
        }

        private void CheckBoxShowAllCheckedChanged(object sender, EventArgs e)
        {
            buttonAdd.Enabled = !checkBoxShowAll.Checked;
            FillDataGrid();
        }

        private void FillComboBoxFromDataTable(ListControl comboBox, DataTable dataTable, string valueMember,
                                                      string displayMember)
        {
            comboBoxNapravlenie.SelectedValueChanged -= ComboBoxNapravlenieSelectedValueChanged;

            comboBox.DataSource = dataTable.AsEnumerable().
                    Distinct(new DataTableComparer(displayMember)).
                    CopyToDataTable().DefaultView;
            comboBox.ValueMember = valueMember;
            comboBox.DisplayMember = displayMember;

            comboBoxNapravlenie.SelectedValueChanged += ComboBoxNapravlenieSelectedValueChanged;
        }

        private void UpdateDataGrid()
        {
            if (_connectionManager.CheckConnection())
            {
                //var str = _aEntityPot.GetSelectQuery();
                _dataTableMain = _dataManager.GetDataTable(_aEntityPot.GetSelectQuery(),
                                                           _connectionManager.GetConnection());
                if (_dataTableMain != null)
                {
                    FillDataGrid();
                    _currentRowIndex = 0;
                }
                else
                {
                    MessageBox.Show("Данные отсутствуют");
                }
            }
            else
            {
                MessageBox.Show("Ошибка подключения к БД.");
                FormClose();
            }
        }

        private void FillDataGrid()
        {
            if (_dataTableMain.Rows.Count > 0)
            {
                buttonDelete.Enabled = true;
                buttonEdit.Enabled = true;
                checkBoxShowAll.Enabled = true;
                comboBoxNapravlenie.Enabled = true;

                if (checkBoxShowAll.Checked)
                {
                    comboBoxNapravlenie.Enabled = false;
                    _napravlenieId = 0;
                    CustomFillDataGrid(_dataTableMain);
                }
                else
                {
                    comboBoxNapravlenie.Enabled = true;

                    FillComboBoxFromDataTable(comboBoxNapravlenie, _dataTableMain, "Hide_IDNapravlenie", "Направление");
                    _napravlenieId = (int) comboBoxNapravlenie.SelectedValue;
                    var dataTableFilteredByNapravlenie = _dataTableMain.AsEnumerable().
                        Where(row => row.Field<int>("Hide_IDNapravlenie") == _napravlenieId).CopyToDataTable();
                    CustomFillDataGrid(dataTableFilteredByNapravlenie);
                }
            }
            else
            {
                buttonDelete.Enabled = false;
                buttonEdit.Enabled = false;
                checkBoxShowAll.Enabled = false;
                comboBoxNapravlenie.Enabled = false;
                comboBoxNapravlenie.DataSource = null;
                CustomFillDataGrid(_dataTableMain);
                MessageBox.Show("Данные отсутствуют");
            }
        }

        private void CustomFillDataGrid(DataTable dataTable)
        {
            if (dataTable != null)
            {
                dataGridView.DataSource = dataTable;
                //скрываем все ненужные столбцы
                for (var i = 0; i < dataGridView.Columns.Count; i++)
                {
                    if (dataGridView.Columns[i].Name.StartsWith("Hide"))
                    {
                        dataGridView.Columns[i].Visible = false;
                    }
                }
            }
            else
            {
                MessageBox.Show("Данные отсутствуют.");
            }
        }
    }
}